#include "povgeometry.h"

#include <QGLWidget>

using namespace POVGeom;

void POVMesh::addTriangle(POVTriangle t)
{
    triangles.push_back(t);
}

void POVMesh::addTexture(POVTexture t)
{
    textures.push_back(t);
}

void POVMesh::setRotX(float r)
{
    rotX = r;
}

void POVMesh::setRotY(float r)
{
    rotY = r;
}
   
void POVMesh::setRotZ(float r)
{
    rotZ = r;
}

void POVMesh::setName(std::string name)
{
    this->name = name;
}

int POVMesh::getNumberOfTris()
{
    return triangles.size();   
}

void POVObject::addMesh(POVMesh * m)
{
    meshes.push_back(m);
}

POVMesh::POVMesh()
{
    rotX=rotY=rotZ=0.0;
    vertexArray=NULL;
    vbufferID=0;
}

int POVMesh::getVertexArray(float * va)
{
    int numTris = getNumberOfTris();

    for(int i = 0; i<numTris;i++)
    {
        POVTriangle t = triangles[i];
        for(int j = 0;j<3;j++)
        {
            va[9*i+j*3+0] = t.pv[j].x;
            va[9*i+j*3+1] = t.pv[j].y;
            va[9*i+j*3+2] = t.pv[j].z;       
        }
    }

}

POVMesh * POVObject::getMesh(int index)
{
    return meshes[index];
}


void POVMesh::generateVertexBufferObjects()
{


    float * tva = (float *) malloc(getNumberOfTris()*3*3*sizeof(float));
    int numTris = getVertexArray(tva);

    glGenBuffers(1,&vbufferID);

    glBindBuffer(GL_ARRAY_BUFFER,vbufferID);
    glBufferData(GL_ARRAY_BUFFER,3*3*sizeof(float)*getNumberOfTris(),tva,GL_STATIC_DRAW);
   
    glBindBuffer(GL_ARRAY_BUFFER,0);

    free(tva);
}

void POVMesh::renderVBO()
{
    if(vbufferID==0)
        generateVertexBufferObjects();

    glEnableClientState(GL_VERTEX_ARRAY);
    glBindBuffer(GL_ARRAY_BUFFER,vbufferID);
    glVertexPointer(3,GL_FLOAT,0,0);

    glDrawArrays(GL_TRIANGLES,0,3*getNumberOfTris()); 
  
    glBindBuffer(GL_ARRAY_BUFFER,0);
    glDisableClientState(GL_VERTEX_ARRAY);
}
